import { createMD5 } from 'hash-wasm';

/**
 * 获取文件的MD5
 */
export function getFileMd5BySlice(file: File, chunkSize = 1024 * 1024 * 6): Promise<string> {
  return new Promise((resolve, reject) => {
    // 总分片数
    const chunks = Math.ceil(file.size / chunkSize);
    let currentChunk = 0;
    createMD5()
    .then((md5) => {
        md5.init();
        const fileReader = new FileReader();
        const loadNext = () => {
          // 切片起始位置
          const start = currentChunk * chunkSize;
          // 切片终止位置
          let end = start + chunkSize;
          if (end >= file.size) {
            end = file.size;
          }
          fileReader.readAsArrayBuffer(file.slice(start, end));
        };
        fileReader.onload = (e) => {
          md5.update(new Uint8Array(e.target!.result as ArrayBuffer));
          currentChunk++;
          if (currentChunk < chunks) {
            loadNext();
          } else {
            const md5Str = md5.digest('hex');
            resolve(md5Str);
          }
        };
        fileReader.onerror = () => {
          reject({ code: -10, msg: '获取文件MD5信息失败,-BD0003' });
        };
        loadNext();
      })
      .catch(() => {
    debugger

        reject({ code: -10, msg: '获取文件MD5信息失败,-BD0004' });
      });
  });
}
